const querystring = require('querystring')
const handelBlogRouter = require('./src/router/blog')
const handelUserRouter = require('./src/router/user')

const getPostData = (req) => {
    return promise = new Promise((resolve, reject) => {
        if(req.method !== 'POST') {
            resolve({})
            return
        }
        if(req.headers['content-type'] !== 'application/json') {
            resolve({})
            return
        }
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            if( !postData ) {
                resolve({})
                return
            }
            resolve(
                JSON.parse(postData)
            )
            return
        })
    })
}


const serverHandle = (req, res) => {
    res.setHeader('Content-type', 'application/json')

    const url = req.url
    //获取path
    const path = url.split('?')[0]
    req.path = path
    //解析query
    req.query = querystring.parse(url.split('?')[1])
    //解析postdata
    getPostData(req).then(data => {
        req.body = data

        const blogResult = handelBlogRouter(req, res)
        if(blogResult) {
            blogResult.then(blogData => {
                res.end(
                    JSON.stringify(blogData)
                )
            })
            return
        }

        const userResult = handelBlogRouter(req, res)
        if(userResult) {
            userResult.then(userData => {
                res.end(
                    JSON.stringify(userData)
                )
            })
            return
        }

        // 未命中路由返回404
        res.writeHeader(404, {'Content-type':'text/plain'})
        res.write('404 Not Found\n')
        res.end()
    })

    
}

module.exports = serverHandle
//process.env.NODE_ENV